package cn.cheqi.recovery.api.controller;


import cn.cheqi.recovery.api.dto.DataGridView;
import cn.cheqi.recovery.api.entity.Building;
import cn.cheqi.recovery.api.entity.Community;
import cn.cheqi.recovery.api.entity.Owner;
import cn.cheqi.recovery.api.entity.User;
import cn.cheqi.recovery.api.mapper.CommunityMapper;
import cn.cheqi.recovery.api.service.CommunityService;
import cn.cheqi.recovery.api.upload.UploadService;
import cn.cheqi.recovery.api.utils.SysFileUtil;
import cn.cheqi.recovery.api.vo.CommunityVO;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  api接口小区前端控制器
 * </p>
 *
 * @author Robin
 * @since 2020-02-23
 */
@RestController("apiCommunityController")
@RequestMapping("/api/community")
public class CommunityController {

    @Autowired
    private CommunityService communityService;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private UploadService uploadService;

    @Value("${aliyun.oss.CommunitySave}")
    private String CommunitySave;

    /**
     * api接口加载所有小区
     * @param communityVO
     * @return
     */
    @RequestMapping("/loadAllCommunities")
    public DataGridView loadAllCommunities(CommunityVO communityVO){

        IPage<Community> page = new Page<>(communityVO.getPage(),communityVO.getLimit());
        QueryWrapper<Community> wrapper = new QueryWrapper<>();
        //商家名称
        String communityName = communityVO.getCommunityName();
        //商家联系方式
        String communityPhone = communityVO.getCommunityPhone();
        //商家详细地址
        String detailedAddress = communityVO.getDetailedAddress();
        //去掉三个查询条件里面的空格
        if (!StringUtils.isBlank(communityName)){
            String sName = communityName.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sName),"community_name",sName);
        }

        if (!StringUtils.isBlank(communityPhone)){
            String sPhone = communityPhone.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sPhone),"community_phone",sPhone);
        }

        if (!StringUtils.isBlank(detailedAddress)){
            String sAddress = detailedAddress.replace(" ", "");
            wrapper.like(!StringUtils.isBlank(sAddress),"detailed_address",sAddress);
        }
        wrapper.orderByDesc("community_id");
        communityService.page(page,wrapper);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",page.getRecords().size());
        //当前页
        map.put("page",page.getCurrent());
        //总页数
        map.put("zpage",page.getPages());
        map.put("list",page.getRecords());
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * api接口添加小区
     * @param communityVO
     * @return
     */
    @PostMapping("/addCommunity")
    @Transactional
    public DataGridView addCommunity(CommunityVO communityVO){
        try {
            if (communityVO.getCommunityPic() == ""){
                communityVO.setCommunityPic("https://rob1n-bucket.oss-cn-shenzhen.aliyuncs.com/recovery/community/default/default.jpg");
            }
            communityService.save(communityVO);
            return new DataGridView(0,"添加成功","");
        } catch (Exception e){
            e.printStackTrace();
            return new DataGridView(0,"添加失败","");
        }
    }

    /**
     * api接口通过小区ID删除小区信息以及图片
     * @param communityVO
     * @return
     */
    @RequestMapping("/deleteCommunityById")
    @Transactional
    public DataGridView deleteCommunityById(CommunityVO communityVO){
        if (communityService.getById(communityVO.getCommunityId()) == null){
            return new DataGridView(1,"该社区信息不存在","");
        }
        try{
            communityService.removeById(communityVO.getCommunityId());
            return new DataGridView(0,"删除成功",null);
        } catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"删除失败",null);
        }
    }

    /**
     * api接口通过ID修改小区信息
     * @param communityVO
     * @return
     */
    @PostMapping("/editCommunity")
    @Transactional
    public DataGridView editCommunityById(CommunityVO communityVO){
        //判断小区是否存在
        Community community = communityService.getById(communityVO.getCommunityId());
        if (community == null){
            return new DataGridView(1,"该小区信息不存在","");
        }
        //判断其他信息是否为空
        if (communityVO.getLongitude()==null && communityVO.getLatitude()==null && communityVO.getAreaAddress()==null && communityVO.getCommunityName()==null
            && communityVO.getCommunityPhone()==null && communityVO.getDetailedAddress()==null && communityVO.getCommunityPic()==null){
            return new DataGridView(1,"您所编辑信息不能为空","");
        }
        try {
            System.out.println(communityVO);
            communityService.updateById(communityVO);
            return new DataGridView(0,"修改成功",null);
        } catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"修改失败",null);
        }
    }


    /**
     * 上传商家图片
     * @param file
     * @return
     */
    @RequestMapping("/uploadCommunityPic")
    @Transactional
    public DataGridView uploadCommunityPics(@RequestParam("communityPic")MultipartFile file){

        try{
            DataGridView dataGridView = uploadService.uploadImg(file,CommunitySave);
            return dataGridView;
        }catch (Exception e){
            e.printStackTrace();
            return new DataGridView(1,"图片上传失败","");
        }
    }

    /**
     * api接口通过小区ID查出该小区下所有未入驻的业主信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllOwnersByCommunityId")
    public DataGridView findAllOwnersByCommunityId(CommunityVO communityVO){
        Community community = communityService.getById(communityVO.getCommunityId());
        if (community == null){
            return new DataGridView(1,"该社区信息不存在","");
        }
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            page.setPages(communityVO.getPage());
            page.setSize(communityVO.getLimit());
        }
        List<Owner> owners = communityMapper.findAllOwnersByCommunityId(communityVO.getCommunityId(),page);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",owners.size());
        //当前页
        map.put("page",page.getCurrent());
        //总页数
        map.put("zpage",page.getPages());
        map.put("list",owners);
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * api接口通过小区ID查出该小区下所有已入驻的业主信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllUsersByCommunityId")
    public DataGridView findAllUsersByCommunityId(CommunityVO communityVO){
        Community community = communityService.getById(communityVO.getCommunityId());
        if (community == null){
            return new DataGridView(1,"该小区信息不存在","");
        }
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            //获取当前页
            page.setCurrent(communityVO.getPage());
            //获取查取条数
            page.setSize(communityVO.getLimit());
        }
        List<User> users = communityMapper.findAllUsersByCommunityId(communityVO.getCommunityId(),page);
        //DTO传输对象
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(1);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("count",users.size());
        //当前页
        map.put("page",page.getCurrent());
        //总页数
        map.put("zpage",page.getPages());
        map.put("list",users);
        dataGridView.setData(map);
        return dataGridView;
    }

    /**
     * 通过小区ID查出该小区下所有楼栋信息
     * @param communityVO
     * @return
     */
    @PostMapping("/findAllBuildingsByCommunityId")
    public DataGridView findAllBuildingsByCommunityId(CommunityVO communityVO){
        Community community = communityService.getById(communityVO.getCommunityId());
        if (community == null){
            return new DataGridView(1,"该社区信息不存在","");
        }
        //分页条件
        Page<Community> page = new Page<>();
        if (communityVO.getPage() != null && communityVO.getLimit() != null){
            page.setCurrent(communityVO.getPage());
            page.setSize(communityVO.getLimit());
        }
        List<Building> buildings = communityMapper.findAllBuildingsByCommunityId(communityVO.getCommunityId(),page);
        DataGridView dataGridView = new DataGridView();
        dataGridView.setCode(0);
        dataGridView.setMsg("");
        Map<Object,Object> map = new HashMap<>();
        map.put("page",page.getCurrent());
        map.put("zpage",page.getPages());
        map.put("count",buildings.size());
        map.put("list",buildings);
        dataGridView.setData(map);
        return dataGridView;
    }
}

